import { Component, ElementRef, Injector, OnInit, ViewChild, ViewEncapsulation } from '@angular/core';
import { appModuleAnimation } from '@shared/animations/routerTransition';
import {ConfigFileDto, ContentRouteServiceProxy, SiteMapServiceProxy
} from '@shared/service-proxies/service-proxies';
import { AppComponentBase } from '@shared/common/app-component-base';
import { IAjaxResponse, TokenService } from 'abp-ng2-module';
import { finalize } from 'rxjs/operators';
import { HttpClient } from '@angular/common/http';
import { AppConsts } from '@shared/AppConsts';
import { FileUploadHelper } from '@shared/helpers/FileUploadHelper';

@Component({
    templateUrl: './sitemap.component.html',
    encapsulation: ViewEncapsulation.None,
    styleUrls: ['./sitemap.component.less'],
    animations: [appModuleAnimation()]
})
export class SitemapComponent extends AppComponentBase implements OnInit {

    badWords: string;
    loading = false;
    
    @ViewChild('fileInputEle2') fileInputEle2: ElementRef;

    uploadUrl: string;

    constructor(
        injector: Injector,
        private _siteMapServiceProxy: SiteMapServiceProxy,
        private _contentRouteServiceProxy: ContentRouteServiceProxy,
        private _httpClient: HttpClient,
        private _tokenService: TokenService
    ) {
        super(injector);

        this.uploadUrl = AppConsts.remoteServiceBaseUrl + '/B/Seo/ImportSeoData';
    }

    ngOnInit(): void {
        this.getBadWords();
    }

    getBadWords() {
        this.loading = true;
        this._siteMapServiceProxy.getSiteMap()
            .pipe(finalize(() => {
                this.loading = false;
            }))
            .subscribe((result: string) => {
                this.badWords = result;
            });
    }

    saveAll() {
        let input = new ConfigFileDto({ content: this.badWords });

        this.loading = true;
        this._siteMapServiceProxy.updateOrCreateSiteMap(input)
            .pipe(finalize(() => {
                this.loading = false;
            }))
            .subscribe(() => {
                this.notify.info(this.l('SavedSuccessfully'));
            });
    }

    reset(){
        this.loading = true;
        this._siteMapServiceProxy.resetSiteMap().pipe(finalize(() => {
            this.loading = false;
        }))
        .subscribe(() => {
            this.getBadWords();
            this.notify.info(this.l('ExecuteSuccessfully'));
        });
    }

    generateContentUrl(){
        this.loading = true;
        this._contentRouteServiceProxy.generateDetailPageUrl().pipe(finalize(() => {
            this.loading = false;
        }))
        .subscribe(() => {
            this.notify.info(this.l('ExecuteSuccessfully'));
        });
    }
    
    uploadExcel(): void {
        this.fileInputEle2.nativeElement.click();
    }

    fileInputEle2Change(e) {
        if (e.target.files && e.target.files.length > 0) {
            let file = e.target.files[0];
            e.target.value = null;

            if (!FileUploadHelper.checkExName(file.name, 'csv|xls|xlsx')) {
                this.notify.error(file.name + '：' + this.l('File_Invalid_Type_Error', ".csv,.xls,.xlsx"));
            }
            else if (!FileUploadHelper.checkMaxSize(file.size, abp.custom.fileUploadMaxSize)) {
                let tempSize = Math.round(file.size / (1024 * 1024) * 100) / 100;
                this.notify.error(file.name + '：' + this.l('File_SizeLimit_Error', abp.custom.fileUploadMaxSize, tempSize));
            } else {
                const formData: FormData = new FormData();
                formData.append('file', file, file.name);
        
                this.loading = true;
                this._httpClient
                    .post<any>(this.uploadUrl, formData)
                    .pipe(finalize(() => this.loading = false))
                    .subscribe(response => {
                        if (response.success) {
                            this.message.success("导入成功,"+ response.result.msg);
                        } else if (response.error != null) {
                            this.message.error("导入失败");
                        }
                    });
            }
        }
    }
}
